package com.speech.net;

import android.content.Context;
import android.content.Intent;
import android.os.Environment;

import com.ontbee.legacyforks.cn.pedant.SweetAlert.SweetAlertDialog;
import com.speech.net.service.DownloadService;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

public class DownloadManager {

    private static File mAppFile;

    public static void download(String url, final Context context) {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(url)
                .build();

        DownloadService service = retrofit.create(DownloadService.class);
        Call<ResponseBody> call = service.download();
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                SweetAlertDialog dialog = new SweetAlertDialog(context, SweetAlertDialog.PROGRESS_TYPE)
                        .setContentText("正在下载");
                dialog.show();
                if (writeResponseBodyToDisk(response.body())) {
                    dialog.dismiss();
                    Intent intent = new Intent();
                    intent.setAction("com.speech.InstallReceiver");
                    intent.putExtra("file_path", mAppFile.getAbsolutePath());

                    mAppFile = null;
                    context.sendBroadcast(intent);
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {

            }
        });

    }

    private static boolean writeResponseBodyToDisk(ResponseBody body) {
        try {
            // todo change the file location/name according to your needs
//            File mAppFile = new File(getExternalFilesDir(null) + File.separator + "Future Studio Icon.png");
            File fileParent = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/speaker_apk/");
            fileParent.mkdirs();
            mAppFile = new File(fileParent, "app.apk");

            InputStream inputStream = null;
            OutputStream outputStream = null;

            try {
                byte[] fileReader = new byte[4096];

                long fileSize = body.contentLength();
                long fileSizeDownloaded = 0;

                inputStream = body.byteStream();
                outputStream = new FileOutputStream(mAppFile);

                while (true) {
                    int read = inputStream.read(fileReader);

                    if (read == -1) {
                        break;
                    }

                    outputStream.write(fileReader, 0, read);

                    fileSizeDownloaded += read;
                }

                outputStream.flush();

                return true;
            } catch (IOException e) {
                return false;
            } finally {
                if (inputStream != null) {
                    inputStream.close();
                }

                if (outputStream != null) {
                    outputStream.close();
                }
            }
        } catch (IOException e) {
            return false;
        }
    }


}
